package com.chhuang.huaao.controller;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.chhuang.core.bean.QueryBean;
import com.chhuang.core.validation.ValidGroupSave;
import com.chhuang.core.validation.ValidGroupUpdate;
import com.chhuang.huaao.bean.HaCustomerQueryBean;
import com.chhuang.huaao.consts.HaConstact;
import com.chhuang.huaao.po.HaCustomer;
import com.chhuang.huaao.service.IHaCustomerService;
import com.chhuang.huaao.service.IHaMachineService;
import com.chhuang.huaao.thread.GeTuiThread;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.utils.Assert;
import com.chhuang.utils.string.Md5Util;

@Controller
@RequestMapping("/system/customer")
public class HaCustomerController {
	private static final Log log = LogFactory.getLog(HaCustomerController.class);
	
	@Autowired
	private IHaCustomerService haCustomerService;
	@Autowired
	private IHaMachineService haMachineService;
	
	/**
	 * 根据客户id获取客户信息
	 * @param customerId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/findCustomerById",method=RequestMethod.POST)
	@ResponseBody
	public Object findCustomerById(String customerId) throws Exception{
		JSONObject json = new JSONObject();
		
		log.debug("客户ID："+customerId);
		if(Assert.isValidString(customerId)){
			HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
			if(customer!=null){
				json.put(SysConstants.Status.SUCCESS, true);
				json.put(SysConstants.Status.RESULT, customer);
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "客户不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "客户ID不为空");
		}
		
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 获取客户列表
	 * @param customerQueryBean
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getList",method=RequestMethod.POST)
	@ResponseBody
	public Object getList(@RequestBody HaCustomerQueryBean customerQueryBean) throws Exception{
		log.debug(customerQueryBean.getPageSize()+";"+customerQueryBean.getPageNum()
				+";"+customerQueryBean.getOrderBy()+";"+customerQueryBean.isDesc()
				+";"+customerQueryBean.isOr());
		
		QueryBean<HaCustomer> queryBean = haCustomerService.seniorQuery(customerQueryBean);
		
		return queryBean;
	}
	
	/**
	 * 添加客户信息
	 * @param customer
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/saveCustomer",method=RequestMethod.POST)
	@ResponseBody
	public Object saveCustomer(@RequestBody @Validated(value={ValidGroupSave.class}) HaCustomer customer, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(haCustomerService.findByCustomerAccount(customer.getCustomerAccount())==null){
			customer.setCustomerPassword(Md5Util.md5(customer.getCustomerAccount(), customer.getCustomerAccount()));
			Date now = new Date();
			customer.setCreateTime(now);
			customer.setModifyTime(now);
			if(haCustomerService.save(customer)>0){
				json.put(HaConstact.CUSTOMER_ID, customer.getCustomerId());
				json.put(SysConstants.Status.SUCCESS, true);
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "保存客户信息失败");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "客户账号已存在");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 修改客户信息
	 * @param customer
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editCustomer",method=RequestMethod.POST)
	@ResponseBody
	public Object editCustomer(@RequestBody @Validated(value={ValidGroupUpdate.class}) HaCustomer customer, BindingResult bindingResult) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(Assert.isValidString(customer.getCustomerId())){
			HaCustomer customerTemp = haCustomerService.findByPrimaryKey(customer.getCustomerId());
			if(customerTemp!=null){
				Date now = new Date();
				customerTemp.setModifyTime(now);
				customerTemp.setCustomerGender(customer.getCustomerGender());
				customerTemp.setCustomerName(customer.getCustomerName());
				customerTemp.setCustomerCompany(customer.getCustomerCompany());
				if(haCustomerService.update(customerTemp)>0){
					json.put(HaConstact.CUSTOMER_ID, customerTemp.getCustomerId());
					json.put(SysConstants.Status.SUCCESS, true);
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "修改客户信息失败");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "客户账号不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "客户ID不为空");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 删除客户信息
	 * @param ids
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/delCustomers/{ids}",method=RequestMethod.DELETE)
	@ResponseBody
	public Object delCustomers(@PathVariable String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] customerIds = ids.split(SysConstants.Symbol.COMMA);
			for(String id : customerIds){
				if(haCustomerService.deleteByPrimaryKey(id)>0){
					haMachineService.updateNullMachineCustomerIds(id);
				}
			}
			json.put(SysConstants.Status.SUCCESS, true);
		}
		log.debug(ids+":::"+json.toString());
		return json;
	}
	
	/**
	 * 重置密码
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/resetCustomerPassword",method=RequestMethod.POST)
	@ResponseBody
	public Object resetCustomerPassword(String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] customerIds = ids.split(SysConstants.Symbol.COMMA);
			for(String customerId : customerIds){
				HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
				if(customer != null){
					customer.setCustomerPassword(Md5Util.md5(customer.getCustomerAccount(), customer.getCustomerAccount()));
					customer.setModifyTime(new Date());
					haCustomerService.update(customer);
				}
			}
			json.put(SysConstants.Status.SUCCESS, true);
		}
		return json;
	}
	
	/**
	 * 锁定/解锁
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/lockedCustomer",method=RequestMethod.POST)
	@ResponseBody
	public Object lockedCustomer(String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] customerIds = ids.split(SysConstants.Symbol.COMMA);
			for(String customerId : customerIds){
				HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
				if(customer != null){
					customer.setLocked(customer.getLocked()==null || !customer.getLocked());
					customer.setModifyTime(new Date());
					haCustomerService.update(customer);
				}
			}
			json.put(SysConstants.Status.SUCCESS, true);
		}
		return json;
	}
	
	/**
	 * 推送消息
	 * @param customerId
	 * @param title
	 * @param content
	 * @param payload
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/pushMessage",method=RequestMethod.POST)
	@ResponseBody
	public Object pushMessage(String customerId, String title, String content, String payload) throws Exception{
		JSONObject json = new JSONObject();
		
		if(Assert.isValidString(customerId) && Assert.isValidString(title) && Assert.isValidString(content)){
			HaCustomer customer = haCustomerService.findByPrimaryKey(customerId);
			if(customer != null && Assert.isValidString(customer.getClientId())){
				JSONObject message = new JSONObject();
				message.put("title", title);
				message.put("content", content);
				if(Assert.isValidString(payload)){
					message.put("payload", payload);
				}else{
					message.put("payload", "");
				}
				new Thread(new GeTuiThread(customer.getClientId(), message)).start();
				json.put(SysConstants.Status.SUCCESS, true);
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "客户账号不存在或者还不支持推送");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "主要参数不为空");
		}
		
		return json;
	}
}
